/**
 * Created by Skipper on 2017/4/14.
 */
import React, {PropTypes} from 'react';
import {Table, Icon, Spin, Button, Modal, Input, message} from 'antd';
import {hashHistory, browserHistory} from 'react-router'
import {connect} from 'react-redux'
import {GoogleMap, withGoogleMap, Marker, InfoWindow} from "react-google-maps";
import withScriptjs from "react-google-maps/lib/async/withScriptjs";
import WebsocketComp from './websocket';
import {
  changeFlightListStatus,
  changeTowerListStatus,
  flightincrease,
  flightdecrease,
  getFlightData
} from '../actions/actions'
import {system_status_flag} from './commonData';
import {formatDate} from './common';
import {gcj02towgs84, wgs84togcj02} from './coordtransform';
var flightsArr = [];
var enter = '';
const FLIGHTICON = require('../images/flight.png')
const AsyncMonitorFlightsGoogleMap = withScriptjs(
  withGoogleMap(
    props => (
      <GoogleMap
        ref={props.onMapLoad}
        defaultZoom={props.mapdefaultProps.zoom}
        defaultCenter={props.mapdefaultProps.center}
        center={props.center}
      >
        {
          props.flightMarkers.map((marker, index) => {
            const onClick = () => props.onMarkerClick(marker);
            const onCloseClick = () => props.onCloseClick(marker);
            return (
              <Marker
                {...marker}
                onClick={onClick}
              >
                {
                  marker.showInfo && (
                    <InfoWindow onCloseClick={onCloseClick}>
                      <div className="maarker-infowindow-container">
                        <p><span>{`Lon：${marker.position.lng}`}</span></p>
                        <p><span>{`Lat：${marker.position.lat}`}</span></p>
                        <p><span>{`编号：${marker.id}`}</span></p>
                        <p><span>{`状态：${marker.baseMode}`}</span></p>
                        <Button type="primary"
                                onClick={()=>props.jumpMonitor({type: 'see', id: `${marker.id}`})}>查看</Button>
                        <Button type="primary"
                                onClick={()=>props.jumpMonitor({type: 'control', id: `${marker.id}`})}
                                onMouseDown={(e)=>props.onMouseDown(e, `${marker.id}`)}
                        >控制</Button>
                      </div>
                    </InfoWindow>
                  )
                }
              </Marker>
            )
          })
        }
      </GoogleMap>
    )
  )
)
class ReactGoogleMapsComp extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isMapLoaded: false,
      mapdefaultProps: {
        center: {
          lat: 29.123456, lng: 119.123456
        },
        zoom: 9
      },
      center: {
        lat: 29.123456, lng: 119.123456
      },
      flightstatedata: [],
      flightMarkers: [],
      flightsList: [
        {key: '火星', id: '火星', time: formatDate()},
      ],
      flightIconData: [
        {id: '火星', lat: 31.123456, lng: 119.123456},
      ],
      WebSocket: null,
      isWebsocket: false,
      forceControlModal: false,
      forceControlFlightID: '',
      forceControlMessageModal: false,
      forceControlMessageValue: '',
      forceControlMessageFlightID: '',
    }
  }

  componentDidMount() {
    /*****给window绑定onkeyup事件,若输入为xunyifly则出现'翻牌'，弹框，想'幸'谁就'幸'谁——折腾了n次终于知道该怎么给window绑定键盘事件*****/
    window.onkeyup = (e)=>this.handleOnKeyUp(e)
  }

  handleMapLoad = (map) => {
    this._mapComponent = map;
    if (map) {
      // console.log('当前缩放级别是  ', map.getZoom());
      const nextMarkers = [
        ...this.state.flightMarkers,
        {
          position: {lat: 31.123456, lng: 119.123456},
          defaultAnimation: 2,
          key: '火星',
          icon: {
            url: FLIGHTICON,
            scaledSize: new google.maps.Size(50, 50),
            size: new google.maps.Size(50, 50),
            origin: new google.maps.Point(0, 0),
            anchor: new google.maps.Point(25, 25),
            labelOrigin: new google.maps.Point(25, 22)
          },
          label: {
            text: '火星',
            color: '#fff',
            fontSize: '12'
          },
          showInfo: false,
          id: '火星',
          baseMode: '人类不可居住',
          flightData: {},
          title: '这是个牛逼的图标'
        },
      ];
      this.setState({
        isMapLoaded: true,
        flightMarkers: nextMarkers,
      });
    }
  }

  handleMarkerClick = (targetMarker) => {
    this.setState({
      flightMarkers: this.state.flightMarkers.map(marker => {
        if (marker === targetMarker) {
          return {
            ...marker,
            showInfo: true,
          };
        }
        return marker;
      }),
    });
  }

  handleCloseClick = (targetMarker) => {
    this.setState({
      flightMarkers: this.state.flightMarkers.map(marker => {
        if (marker === targetMarker) {
          return {
            ...marker,
            showInfo: false,
          };
        }
        return marker;
      }),
    });
  }

  handleJumpMonitor = (arg) => {
    var route = this.props.location.pathname;
    console.log('当前route 是 ', route, ' this.props.location ', this.props.location, arg);
    if (arg.type == 'see') {
      window.open(`#/monitor?id=${arg.id}`);
    } else if (arg.type == 'control') {
      window.open(`#/monitor?id=${arg.id}`);
      // let WSData = [
      //   253,
      //   arg.id
      // ];
      // console.log('websocket send data is ', WSData, this.state.WebSocket);
      // this.state.WebSocket.send(JSON.stringify(WSData));
    }
    // hashHistory.push('/monitor');
  }

  /*****输入xunyifly出现强制夺权弹框
   *
   * @param e
   */
  handleOnKeyUp = (e)=> {
    // console.log('key event is ',e,e.keyCode)
    let _this = this;
    if (this.state.isMapLoaded) {
      if (e.keyCode == 13) {
        if (enter == 'xunyifly') {
          _this.setState({
            forceControlModal: true,
          })
        }
        enter = '';
      } else {
        enter += String.fromCharCode(e.keyCode).toLowerCase();
      }
    }
  };

  /*****给需要强制夺权的flightmarker绑定特定键盘事件
   *
   * @param e
   * @param id
   */
  handleOnMouseDown = (e, id) => {
    let _this = this;
    if (e.ctrlKey == true) {
      _this.setState({
        forceControlMessageModal: true,
        forceControlMessageFlightID: id,
      })
    }
  }

  forceControlInput = (e)=> {
    this.setState({
      forceControlFlightID: e.target.value,
    })
  };

  forceControlOk = (e)=> {
    if (!this.state.forceControlFlightID) {
      message.warning('没翻牌（飞机id为空），你要自娱自乐吗？')
    } else {
      window.open(`http://g1.xyitech.com:9999/token?fid=${this.state.forceControlFlightID}`);
      this.setState({
        forceControlModal: false,
        forceControlFlightID: '',
      });
      enter = '';
    }
  };

  forceControlCancel = (e)=> {
    this.setState({
      forceControlModal: false,
      forceControlFlightID: '',
    });
  };

  forceControlMessageChange = (e)=> {
    this.setState({
      forceControlMessageValue: e.target.value,
    })
  };

  forceControlMessageOk = ()=> {
    let token = this.state.forceControlMessageValue;
    if (!token) {
      message.warning('沉默(输入为空）不算暗号')
    } else {
      window.open(`#/monitor?id=${this.state.forceControlMessageFlightID}&t=${encodeURIComponent(token)}`);
      this.setState({
        forceControlMessageModal: false,
        forceControlMessageValue: '',
      });
    }
  };

  forceControlMessageCancel = (e)=> {
    this.setState({
      forceControlMessageModal: false,
      forceControlMessageValue: '',
    });
  };

  /*****
   * websocket数据处理
   */
  websocketOnPen(arg) {
    console.log('ws is ', arg);
    /*****WS存在且readyState==1，即已连接*****/
    if (arg.target.readyState && arg.target.readyState == 1) {
      this.setState({
        isWebsocket: true,
        WebSocket: arg.target,
      })
    }
  }

  handleData(data) {
    let _this = this;
    if (data == 'undefined') {
      return;
    }
    let gettype = Object.prototype.toString;
    let resdt, msgid, tId;
    let begin = 0;
    if (gettype.call(data) == '[object ArrayBuffer]') {
      resdt = new DataView(data);
      msgid = resdt.getUint8(begin);
    } else {
      resdt = JSON.parse(data);
      msgid = resdt[begin];
      tId = resdt[1];
    }
    // console.log('新协议数据是 ', data, ' 数据类型是  ', typeof data, '  ', gettype.call(data), '  ');
    // console.log('msgid is ', msgid);
    /*======飞机数据======*/
    if (msgid == 1) {
      /*****心跳包heartbeat*****/
      begin += 1;
      let id = (resdt[begin]).toString();
      let heartbeat = {};
      heartbeat['id_uav_xyi'] = id;
      begin += 1;
      heartbeat['id_iso_xyi'] = resdt[begin];
      begin += 1;
      heartbeat['base_mode'] = resdt[begin];
      begin += 1;
      heartbeat['system_status'] = resdt[begin];
      begin += 1;
      heartbeat['xylink_version'] = resdt[begin];
      begin += 1;
      /*****flightsArr保存上线的飞机id,注意数据类型，indexOf使用的是'==='*****/
      if (flightsArr.indexOf(id) == -1) {
        flightsArr.push(id);
        _this.props.flightincrease(1);
        _this.setState({
          flightMarkers: [
            ..._this.state.flightMarkers,
            {
              position: {
                lat: 29.123456,
                lng: 119.123456,
              },
              defaultAnimation: 2,
              key: `${id}${Math.random()}`,
              icon: {
                url: FLIGHTICON,
                scaledSize: new google.maps.Size(50, 50),
                size: new google.maps.Size(50, 50),
                origin: new google.maps.Point(0, 0),
                anchor: new google.maps.Point(25, 25),
                labelOrigin: new google.maps.Point(25, 22)
              },
              label: {
                text: `${id}`,
                color: '#fff',
                fontSize: '12'
              },
              showInfo: false,
              baseMode: system_status_flag[heartbeat.base_mode],
              id: `${id}`,
              flightData: {
                heartbeat: heartbeat,
              },
              title: id.toString() + '牛逼的图标'
            },
          ],
          flightIconData: [
            ..._this.state.flightIconData,
            {lat: 29.123456, lng: 119.123456, id: id,}
          ],
          flightsList: [
            ..._this.state.flightsList,
            {key: id, id: id, time: formatDate()}
          ],
        });
      } else {
        _this.setState({
          flightMarkers: _this.state.flightMarkers.map(marker=> {
            if (id == marker.id) {
              return {
                ...marker,
                flightData: {
                  ...marker.flightData,
                  heartbeat: heartbeat,
                }
              }
            }
            return marker
          }),
        })
      }
    } else if (msgid == 2) {
      /*****电池battery_status*****/
      begin += 1;
      let id = (resdt[begin]).toString();
      begin += 1;
      let battery_status = {};
      battery_status['time_std_s'] = 0;
      battery_status['time_std_s'] = resdt[begin];
      begin += 1;
      battery_status['voltages'] = [];
      for (let i = 0; i < 10; i++) {
        battery_status['voltages'][i] = resdt[begin];
        begin += 1;
      }
      battery_status['current_battery'] = resdt[begin];
      begin += 1;
      battery_status['battery_remaining'] = resdt[begin];
      begin += 1;
      _this.setState({
        flightMarkers: _this.state.flightMarkers.map(marker=> {
          if (id == marker.id) {
            return {
              ...marker,
              flightData: {
                ...marker.flightData,
                battery_status: battery_status,
              }
            }
          }
          return marker
        }),
      })
    } else if (msgid == 3) {
      /*****相对坐标local_position_ned*****/
      begin += 1;
      let id = (resdt[begin]).toString();
      begin += 1;
      let local_position_ned = {};
      local_position_ned['time_std_s'] = resdt[begin];
      begin += 1;
      local_position_ned['x'] = resdt[begin].toFixed(2);
      begin += 1;
      local_position_ned['y'] = resdt[begin].toFixed(2);
      begin += 1;
      local_position_ned['z'] = resdt[begin].toFixed(2);
      begin += 1;
      local_position_ned['vx'] = resdt[begin].toFixed(2);
      begin += 1;
      local_position_ned['vy'] = resdt[begin].toFixed(2);
      begin += 1;
      local_position_ned['vz'] = resdt[begin].toFixed(2);
      begin += 1;
      local_position_ned['dis_m'] = resdt[begin].toFixed(1);
      begin += 1;
      _this.setState({
        flightMarkers: _this.state.flightMarkers.map(marker=> {
          if (id == marker.id) {
            return {
              ...marker,
              flightData: {
                ...marker.flightData,
                local_position_ned: local_position_ned,
              }
            }
          }
          return marker
        }),
      })
    } else if (msgid == 4) {
      /*****绝对坐标global_position_int*****/
      begin += 1;
      let id = (resdt[begin]).toString();
      begin += 1;
      let global_position_int = {};
      global_position_int['time_std_s'] = resdt[begin];
      begin += 1;
      global_position_int['relative_alt'] = resdt[begin];
      begin += 1;
      global_position_int['hdg'] = resdt[begin];
      begin += 1;
      _this.setState({
        flightMarkers: _this.state.flightMarkers.map(marker=> {
          if (id == marker.id) {
            return {
              ...marker,
              flightData: {
                ...marker.flightData,
                global_position_int: global_position_int,
              }
            }
          }
          return marker
        }),
      })
    } else if (msgid == 5) {
      /*****GPS数据gps_raw*****/
      begin += 1;
      let id = (resdt[begin]).toString();
      begin += 1;
      let gps_raw = {};
      gps_raw['time_std_s'] = resdt[begin];
      begin += 1;
      gps_raw['fix_type'] = resdt[begin];
      begin += 1;
      let lat = parseFloat(resdt[begin]);
      gps_raw['lat_gps'] = lat;
      begin += 1;
      let lon = parseFloat(resdt[begin]);
      gps_raw['lon_gps'] = lon;
      begin += 1;
      let alt = parseFloat(resdt[begin]);
      gps_raw['alt_gps'] = alt;
      begin += 1;
      gps_raw['eph'] = resdt[begin];
      begin += 1;
      gps_raw['epv'] = resdt[begin];
      begin += 1;
      gps_raw['vel_gps'] = resdt[begin];
      begin += 1;
      gps_raw['cog'] = resdt[begin];
      begin += 1;
      gps_raw['satellites_visible'] = resdt[begin];
      begin += 1;
      /*****真实坐标（wgs84）转国测局坐标（火星坐标即地图显示坐标）*****/
      let curPosition = {
        lat: wgs84togcj02(lon, lat)[1],
        lng: wgs84togcj02(lon, lat)[0],
      };
      // console.log('转之前坐标：', {lat: lat, lng: lon}, '  转之后坐标 ：', curPosition)
      _this.setState({
        flightMarkers: _this.state.flightMarkers.map(marker=> {
          if (id == marker.id) {
            return {
              ...marker,
              position: curPosition,
              flightData: {
                ...marker.flightData,
                gps_raw: gps_raw,
              }
            }
          }
          return marker
        }),
        flightIconData: _this.state.flightIconData.map(marker=> {
          if (id == marker.id) {
            return {
              ...marker,
              lat: curPosition.lat,
              lng: curPosition.lon
            }
          }
          return marker
        }),
      });
    } else if (msgid == 250) {
      // console.log('msgid', msgid, '  返回数据是  ', resdt);
      begin += 1;
      let id = (resdt[begin]).toString();
      begin += 2;
      let len = resdt.length;
      let TempToken = resdt.slice(begin, len);
      let s;
      let token = '';
      for (s in TempToken) {
        token += String.fromCharCode(TempToken[s]);
      }
      window.open(`#/monitor?id=${id}&t=${encodeURIComponent(token)}`);
    } else if (msgid == 254) {
      // console.log('msgid', msgid);
      begin += 1;
      let id = (resdt[begin]).toString();
      begin += 1;
      let type = resdt[begin];
      if (type == 0) {
        _this.timer = setTimeout(function () {
          flightsArr = flightsArr.map(flight=> {
            if (flight != id) {
              return flight
            }
          });
          /*****尼玛，map和filter方法不熟练，坑死我了****/
          _this.props.flightdecrease(1);
          _this.state.flightsList = _this.state.flightsList.filter(flight=> {
            return flight.id != id
          });
          _this.setState({
            flightMarkers: _this.state.flightMarkers.filter(marker=> {
              return marker.id != id
            })
          });
          // console.log('254 flightsmarkers ', _this.state.flightMarkers)
        }, 5000);
      }
    }
  }

  handleErroData(data) {
    console.log('websocket发生发生错误，请重试', data)
  }

  locationIcon(arg) {
    // console.log('当前定位图标数据是 ', arg);
    let _this = this;
    let id = arg.id;
    let flightMarkers = this.state.flightMarkers;
    for (var i = 0; i < flightMarkers.length; i++) {
      // console.log('当前行id is  ', id, '  flightMarkers id is ', flightMarkers[i].id)
      if (id == flightMarkers[i].id) {
        let curcenter = {
          lat: flightMarkers[i].position.lat,
          lng: flightMarkers[i].position.lng
        }
        _this.setState({
          center: curcenter
        });
        // console.log(' 中心数据是  ', _this.state.center)
      }
    }
  }

  render() {
    let {flightliststatus, towerliststatus, flightincrease, flightdecrease, flightnum, flightlistdata}=this.props;
    var flightCls = 'flight-list';
    if (flightliststatus) {
      flightCls += ' active'
    }
    var towerCls = 'tower-list';
    if (towerliststatus) {
      towerCls += ' active'
    }
    const flightcolumns = [
      {
        title: 'id',
        dataIndex: 'id',
        key: 'name',
        render: text => <a href="#">{text}</a>,
      }, {
        title: '上线时刻',
        dataIndex: 'time',
        key: 'age',
      }, {
        title: '定位',
        key: 'action',
        render: (text, record) => (
          <span className="location-span" onClick={()=>this.locationIcon(record)}><Icon type="eye"/></span>
        ),
      }];
    const towercolumns = [
      {
        title: 'id',
        dataIndex: 'name',
        key: 'name',
        render: text => <a href="#">{text}</a>,
      },
      {
        title: '机场',
        dataIndex: 'aid',
        key: 'aid',
      },
      {
        title: '上线时刻',
        dataIndex: 'time',
        key: 'time',
      },
      {
        title: '定位',
        key: 'action',
        render: (text, record) => (
          <span>
     <Icon type="eye"/>
    </span>
        ),
      }];
    const towerdata = [
      {
        key: '1',
        name: ' Brown',
        aid: '火星',
        time: 'New',
      }, {
        key: '2',
        name: 'Green',
        aid: '火星',
        time: '12',
      }, {
        key: '3',
        name: 'Black',
        aid: '火星',
        time: '12',
      }];
    const FlightTowerTableList = () => <div className="google-img-container">
      <div className="flight-item">
        <div id="flight-no" className="main-package-no main-margin-top"
             onClick={()=>this.props.changeFlightListStatus()}>{flightnum}
        </div>
        <div className={flightCls}>
          <div className="arrow-container">
            <div className="arrow">
              <div className="arrowtips"></div>
            </div>
          </div>
          <Table
            columns={flightcolumns}
            bordered
            pagination={false}
            dataSource={this.state.flightsList}
          />
        </div>
      </div>
      <div className="flight-item">
        <div className="main-tower-no" onClick={()=>this.props.changeTowerListStatus()}>0</div>
        <div className={towerCls}>
          <div className="arrow-container">
            <div className="arrow">
            </div>
          </div>
          <div className="thead-container">
            <Table
              columns={towercolumns}
              bordered
              pagination={false}
              dataSource={towerdata}
            />
          </div>
        </div>
      </div>
    </div>;
    return (
      <div className="map-container">
        <AsyncMonitorFlightsGoogleMap
          googleMapURL="http://ditu.google.cn/maps/api/js?v=3.exp&language=zh-CN&libraries=geometry,drawing&key=AIzaSyDEK4XKx_F2_R76kuxE_igcWbZpu1n14BQ&sensor=false&libraries=visualization"
          loadingElement={
            <div style={{height: `100%`}}>
              <Spin
                size="large"
                style={{
                  display: `block`,
                  width: `80px`,
                  height: `80px`,
                  margin: `150px auto`,
                  animation: `fa-spin 3s infinite linear`,
                }}
              />
            </div>
          }
          loading={this.state.loading}
          containerElement={
            <div style={{height: `100%`}}/>
          }
          mapElement={
            <div style={{height: `100%`}}>
            </div>
          }
          mapdefaultProps={this.state.mapdefaultProps}
          center={this.state.center}
          flightMarkers={this.state.flightMarkers}
          onMapLoad={this.handleMapLoad}
          onMarkerClick={this.handleMarkerClick}
          onCloseClick={this.handleCloseClick}
          jumpMonitor={this.handleJumpMonitor}
          onMouseDown={this.handleOnMouseDown}
        />
        {
          this.state.isMapLoaded ? <WebsocketComp url='ws://jieyan.xyitech.com/control/create'
                                                  onOpen={this.websocketOnPen.bind(this)}
                                                  onMessage={this.state.isWebsocket ? this.handleData.bind(this) : this.websocketOnPen.bind(this)}
                                                  onError={this.handleErroData.bind(this)}
                                                  binaryType='arraybuffer'
                                                  debug={true}/> : ''
        }

        <FlightTowerTableList/>
        <Modal
          title="翻牌"
          okText="拍翻"
          width={240}
          visible={this.state.forceControlModal}
          onOk={this.forceControlOk}
          onCancel={this.forceControlCancel}
        >
          <div className="force-control">
            <p>飞机ID</p>
            <Input placeholder='想幸谁，就翻谁的牌' value={this.state.forceControlFlightID} onChange={this.forceControlInput}/>
          </div>
        </Modal>
        <Modal
          title="暗号"
          okText="芝麻开门"
          cancelText="点错了"
          width={240}
          visible={this.state.forceControlMessageModal}
          onOk={this.forceControlMessageOk}
          onCancel={this.forceControlMessageCancel}
        >
          <div className="force-control">
            <p>请输入暗号</p>
            <Input placeholder='暗号：天王盖地虎！' value={this.state.forceControlMessageValue}
                   onChange={this.forceControlMessageChange}/>
          </div>
        </Modal>
      </div>
    );
  }
}
const getBasicData = state => {
  return {
    flightliststatus: state.update.flightliststatus,
    towerliststatus: state.update.towerliststatus,
    flightnum: state.update.flightnum,
    flightdata: state.update.flightdata,
  }
}
export default connect(
  getBasicData,
  {changeFlightListStatus, changeTowerListStatus, flightincrease, flightdecrease, getFlightData}
)(ReactGoogleMapsComp)
